package com.emily.test.controller;

import com.alibaba.fastjson.JSONObject;
import com.emily.test.constant.ReturnValueConstants;
import com.emily.test.controller.result.ResponseResult;
import com.emily.test.model.*;
import com.emily.test.service.*;
import com.emily.test.utils.ConstentUtil;
import com.emily.test.utils.HeaderUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController

@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping(value = "tRoleResourceController")
@Api(value = "TRoleResourceApi", description = "TRoleResource接口类", position = 1, produces = MediaType.APPLICATION_JSON_VALUE)
public class TRoleResourceController {

    private Logger logger = LoggerFactory.getLogger(TResourceController.class);

    @Autowired
    private TRoleResourceService tRoleResourceService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private TResourceService tResourceService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private RCompanyRoleService rCompanyRoleService;

    @Autowired
    private TCompanyResourceService tCompanyResourceService;

    /**
     * 插入角色与资源关联表信息
     * @param jsonObject 包含角色（roleId）与资源（resourceIds）关联表集合 ，其中roleId格式为Integer，resourceIds格式为List集合
     * @return
     */
    @ApiOperation(value="插入角色与资源的对应关系", notes="tRoleResource")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色ID", required = true),
            @ApiImplicitParam(name = "resourceIds", value = "资源ID", required = true)
    })
    @PostMapping(value = "insertTRoleResourceInfo")
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public ResponseResult insertTRoleResourceInfo(@RequestBody JSONObject jsonObject){
        Map<String,Object> map=jsonObject.getInnerMap();
        try {
                 int num=tRoleResourceService.insertTRoleResourceInfo(map);
                 if(num==0){
                     logger.error("未插入任何角色与资源关联表的数据,数据集合={}",map);
                     return ResponseResult.fail(ReturnValueConstants.ADD_FAILURE);
                 }
                 logger.info("插入t_role_resource成功，集合map={}",map);
                 return ResponseResult.success(ReturnValueConstants.ADD_SUCCESS,num);
        } catch (Exception e) {
            logger.error("插入t_role_resource异常:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.ADD_FAILURE);
        }
    }

    /**
     *根据角色ID删除对应的资源ID
     * @param roleId 角色ID
     * @return
     */
    @ApiOperation(value="根据角色ID删除对应的资源ID", notes="TRoleResource")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色ID", required = true)
    })
    @PostMapping(value = "deleteTRoleResourceByRoleId/{roleId}")
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public ResponseResult deleteTRoleResourceByRoleId(@PathVariable("roleId") Integer roleId){
        if(ConstentUtil.isEmpty(roleId)){
            return ResponseResult.fail("角色"+ReturnValueConstants.IS_NOT_ALLOW_NULL);
        }
        try {
            int num= tRoleResourceService.deleteTRoleResourceByRoleId(roleId);
            logger.info("删除t_role_resource成功，删除数量={}",num);
            return ResponseResult.success(ReturnValueConstants.DELATE_SUCCESS,num);
        } catch (Exception e) {
            logger.error("删除t_role_resource异常:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.DELATE_FAILURE);
        }
    }

    /**
     *根据角色IDs删除对应的资源ID
     * @param jsonObject 角色ID
     * @return
     */
    @ApiOperation(value="根据角色IDs删除对应的资源ID", notes="TRoleResource")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "角色IDs", required = true)
    })
    @PostMapping(value = "deleteTRoleResourceByRoleIds")
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public ResponseResult deleteTRoleResourceByRoleId(@RequestBody JSONObject jsonObject){
        String ids=jsonObject.getString("ids").replaceAll("\\[","").replaceAll("]","");
        String[] idStr=ids.split(",");
        List<Integer> tRoleIds=new ArrayList<Integer>();
        if(idStr.length !=0){
            for( int i=0;i<idStr.length;i++){
                tRoleIds.add(Integer.valueOf(idStr[i].trim()));
            }
        }
        try {
            int num= tRoleResourceService.deleteTRoleResourceByRoleIds(tRoleIds);
            logger.info("删除t_role_resource成功，删除数量={}",num);
            return ResponseResult.success(ReturnValueConstants.DELATE_SUCCESS,num);
        } catch (Exception e) {
            logger.error("删除t_role_resource异常:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.DELATE_FAILURE);
        }
    }
    /**
     * 根据角色ID查询对应的资源信息列表
     * @param roleId 角色ID
     * @return
     */
    @ApiOperation(value="根据角色ID查询所有相关资源ID", notes="TRoleResource")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色ID", required = true)
    })
    @PostMapping(value = "selectTReSourceIDByRoleId/{roleId}")
    public ResponseResult selectTReSourceIDByRoleId(@PathVariable("roleId") Integer roleId){
        if(ConstentUtil.isEmpty(roleId)){
            logger.info("查询t_role_resource失败,roleId={}",roleId);
            return ResponseResult.fail("角色"+ReturnValueConstants.IS_NOT_ALLOW_NULL);
        }
        try {
            List<TRoleResource> tRoleResourceList= tRoleResourceService.selectTReSourceIDListByRoleId(roleId);
            logger.info("查询t_role_resource成功，list={}",tRoleResourceList);
            return ResponseResult.success(ReturnValueConstants.QUERY_SUCCESS,tRoleResourceList);
        } catch (Exception e) {
            logger.error("查询t_role_resource异常:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }


    /**
     * 更新角色与资源关系信息表
     * @param jsonObject 包含角色（roleId）与资源（resourceIds）关联表集合 ，其中roleId格式为Integer，resourceIds格式为List集合
     * @return
     */
    @ApiOperation(value="修改角色ID对应的资源ID信息", notes="TRoleResource")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色ID", required = true),
            @ApiImplicitParam(name = "resourceIds", value = "资源ID")
    })
    @PostMapping(value = "updateTReSourceIdInfo")
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public ResponseResult updateTReSourceIdInfo(@RequestBody JSONObject jsonObject){
        System.out.println(jsonObject);
        Map<String,Object> map=jsonObject.getInnerMap();
        Integer roleId= Integer.parseInt(map.get("roleId").toString());
        if(ConstentUtil.isEmpty(roleId)){
            logger.info("修改t_role_resource失败,roleId={}",roleId);
            return ResponseResult.fail("角色"+ReturnValueConstants.IS_NOT_ALLOW_NULL);
        }
        try {
            //删除原有角色与资源的对应关系
            int delNum=tRoleResourceService.deleteTRoleResourceByRoleId(roleId);
            logger.info("删除t_role_resource成功，total={}",delNum);

            //增加新的角色与资源的绑定关系，如果资源信息集合为空，则不需插入
            if(ConstentUtil.isEmpty((List<Integer>)map.get("resourceIds"))){
                logger.info("增加t_role_resource成功，map={}",map);
                return ResponseResult.success(ReturnValueConstants.ADD_SUCCESS,0);
            }
            int addNum=tRoleResourceService.insertTRoleResourceInfo(map);

            logger.info("修改t_role_resource成功，新增条数:{}",addNum);
            return ResponseResult.success(ReturnValueConstants.UPDATE_SUCCESS,addNum);
        } catch (Exception e) {
            logger.error("更新t_role_resource表异常:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.UPDATE_FAILURE);
        }
    }

    /**
     * 根据角色ID获取角色信息以及所有的资源信息集合，其中公司已经有的资源信息添加selected=1属性，没有的则为selected=0.
     * @param jsonObject
     * @return
     */
    @ApiOperation(value="根据角色ID获取角色信息以及所有的资源信息集合，其中公司已经有的资源信息添加selected=1属性，" +
            "没有的则为selected=0.", notes="TRoleResource")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "角色ID", required = true)
    })
    @PostMapping(value = "getRoleAndAllResourceInfoByRoleId")
    public ResponseResult getRoleAndAllResourceInfoByRoleId(@RequestBody JSONObject jsonObject){
        try {
            //角色ID
            Integer roleId=jsonObject.getInteger("id");

            //根据角色ID获取角色信息
            TRole tRole=roleService.selectRoleById(roleId);

            //获取角色已经存在的资源信息列表
            List list=new ArrayList();
            list.add(roleId);
            List<Map<String,Object>> tResourceLists= tResourceService.selectTReSourceInfoListByRoleIds(list);

            //获取所有启用的资源信息
            TResource tResource=new TResource();
            tResource.setState(1);
            List<TResource> tResourceList=tResourceService.selectResourceListByCondition(tResource);

            Map<String,Object> returnMapList=new HashMap<String,Object>();
            //将公司信息放入map
            returnMapList.put("id",tRole.getId());
            returnMapList.put("rName",tRole.getrName());
            returnMapList.put("rCode",tRole.getrCode());
            returnMapList.put("roleState",tRole.getState());
            returnMapList.put("roleSerial",tRole.getSerial());
            returnMapList.put("roleDescription",tRole.getDescription());
            returnMapList.put("roleUpdateTime",tRole.getUpdateTime());

            //将资源信息放入集合
            List<Map<String,Object>> inputList=new ArrayList<Map<String,Object>>();
            if(!ConstentUtil.isEmpty(tResourceList)){
                for(TResource tResource1 : tResourceList){

                    int allResourceId=tResource1.getId();

                    Map<String,Object> resourceMap=new HashMap<>();
                    resourceMap.put("resourceId",tResource1.getId());
                    resourceMap.put("resName",tResource1.getResName());
                    resourceMap.put("resourceDescription",tResource1.getDescription());
                    resourceMap.put("pageurl",tResource1.getPageurl());
                    resourceMap.put("img",tResource1.getImg());
                    resourceMap.put("resourceState",tResource1.getState());
                    resourceMap.put("pid",tResource1.getPid());
                    resourceMap.put("resourceUpdateTime",tResource1.getUpdateTime());

                    if(!ConstentUtil.isEmpty(tResourceLists)){
                        for(Map<String,Object> rMap : tResourceLists){
                            int partResourceId=(int) rMap.get("resourceId");
                            //添加公司含有的角色信息到map，并且为其添加属性selected ： true
                            if(allResourceId==partResourceId){
                                resourceMap.put("selected","1");
                                break;
                            }else{
                                resourceMap.put("selected","0");
                            }
                        }
                    }else{
                        resourceMap.put("selected","0");
                    }
                    inputList.add(resourceMap);
                }
            }
            returnMapList.put("resourceList",inputList);
            logger.info("查询角色资源信息成功:{}",returnMapList);
            return ResponseResult.success(returnMapList);
        } catch (Exception e) {
            logger.error("查询角色资源信息异常",e);
            e.printStackTrace();
            return ResponseResult.fail("查询失败");
        }

    }

    @ApiOperation(value="根据登录人公司查看角色与资源信息", notes="TRoleResource")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rName", value = "角色名称")
    })
    @PostMapping(value = "getRoleAndAllResourceInCompanyInfoList")
    public ResponseResult getRoleAndAllResourceInCompanyInfoList(@RequestBody(required = false) JSONObject jsonObject,HttpServletRequest request){

        String rName=null;
        if(!ConstentUtil.isEmpty(jsonObject)){
           rName= jsonObject.getString("rName");
        }
        Integer companyId=HeaderUtil.getCompanyId(request,redisService);
        List<TRole> roleList=new ArrayList<TRole>();
        try {
            //获取公司下的角色信息列表
            List<RCompanyRole> lists = rCompanyRoleService.selectRoleIdListByCompanyId(companyId);
            if(ConstentUtil.isEmpty(lists)){
               return null;
            }
            //获取角色已经存在的资源信息列表
            List list=new ArrayList();

            for(RCompanyRole rCompanyRole:lists){
                TRole tRole = roleService.selectRoleById(rCompanyRole.getRoleId());
                roleList.add(tRole);
                list.add(tRole.getId());
            }
            List<Map<String,Object>> tResourceLists= tResourceService.selectTReSourceInfoListByRoleIdIns(list,rName);
            List<Map<String,Object>> tResourceLi =new ArrayList<Map<String,Object>>();
            if(!ConstentUtil.isEmpty(tResourceLists)){
//                for(Map res : tResourceLists){
//                    Map<String,Object> comMap=new HashMap<String,Object>();
//                    comMap.put("rName",res.get("rName"));
//                    comMap.put("rCode",res.get("rCode"));
//                    comMap.put("roleId",res.get("roleId"));
//                    comMap.put("roleUpdateTime",res.get("roleUpdateTime"));
//                    comMap.put("roleState",res.get("roleState"));
//                    comMap.put("serial",res.get("serial"));
//                    comMap.put("description",res.get("description"));
//                    comMap.put("data",res);
//                }
                for(TRole tRole : roleList){
                    boolean flag=false;
                    String roleCode=tRole.getrCode();
                    Map<String,Object> comMap=ConstentUtil.beanToMap(tRole);
                    List ls=new ArrayList();
                    for(Map res : tResourceLists){
                        String rCode= (String) res.get("rCode");
                        if(roleCode.equals(rCode)){
                            flag=true;
                            ls.add(res);
                        }
                    }
                    if(flag){
                        comMap.put("data",ls);
                        tResourceLi.add(comMap);
                    }
                }
            }
            logger.info("查询角色资源信息成功:{}",tResourceLi);
            return ResponseResult.success(ReturnValueConstants.QUERY_SUCCESS,tResourceLi);
        } catch (Exception e) {
            logger.error("查询角色资源信息异常",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }

    /**
     * 根据角色ID获取角色信息以及所有的公司已有的资源信息集合，其中角色已经有的资源信息添加selected=1属性，没有的则为selected=0.
     * @param jsonObject
     * @return
     */
    @ApiOperation(value="根据角色ID获取角色信息以及所有的公司已有的资源信息集合，" +
            "其中角色已经有的资源信息添加selected=1属性，" +
            "没有的则为selected=0.", notes="TRoleResource")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "角色ID", required = true)
    })
    @PostMapping(value = "getRoleAndAllResourceInCompanyInfoByRoleId")
    public ResponseResult getRoleAndAllResourceInCompanyInfoByRoleId(@RequestBody JSONObject jsonObject,HttpServletRequest request){
        Integer companyId=HeaderUtil.getCompanyId(request,redisService);
        try {
            //角色ID
            Integer roleId=jsonObject.getInteger("id");

            //根据角色ID获取角色信息
            TRole tRole=roleService.selectRoleById(roleId);

            //获取角色已经存在的资源信息列表
            List list=new ArrayList();
            list.add(roleId);
            List<Map<String,Object>> tResourceLists= tResourceService.selectTReSourceInfoListByRoleIds(list);

            //获取所有公司已经拥有的启用资源信息
            TResource tResource=new TResource();
            tResource.setState(1);
//            List<TResource> tResourceList=tResourceService.selectResourceListByCondition(tResource);
            //根据公司ID获取公司已经拥有的资源信息列表
            List<Map<String,Object>> tResourceMapList=tCompanyResourceService.selectTCompanyResourceInfoByCompanyId(companyId);

            Map<String,Object> returnMapList=new HashMap<String,Object>();
            //将角色信息放入map
            returnMapList.put("id",tRole.getId());
            returnMapList.put("rName",tRole.getrName());
            returnMapList.put("rCode",tRole.getrCode());
            returnMapList.put("roleState",tRole.getState());
            returnMapList.put("roleSerial",tRole.getSerial());
            returnMapList.put("roleDescription",tRole.getDescription());
            returnMapList.put("roleUpdateTime",tRole.getUpdateTime());

            //将资源信息放入集合
            List<Map<String,Object>> inputList=new ArrayList<Map<String,Object>>();
            if(!ConstentUtil.isEmpty(tResourceMapList)){
                for(Map<String,Object> tResource1 : tResourceMapList){

                    int allResourceId= (int) tResource1.get("id");

                    Map<String,Object> resourceMap=new HashMap<>();
                    resourceMap.put("resourceId",tResource1.get("id"));
                    resourceMap.put("resName",tResource1.get("resourceName"));
                    resourceMap.put("resourceDescription",tResource1.get("description"));
                    resourceMap.put("pageurl",tResource1.get("pageurl"));
                    resourceMap.put("img",tResource1.get("img"));
                    resourceMap.put("resourceState",tResource1.get("state"));
                    resourceMap.put("pid",tResource1.get("pid"));
                    resourceMap.put("resourceUpdateTime",tResource1.get("updateTime"));

                    if(!ConstentUtil.isEmpty(tResourceLists)){
                        for(Map<String,Object> rMap : tResourceLists){
                            int partResourceId=(int) rMap.get("resourceId");
                            //添加公司含有的角色信息到map，并且为其添加属性selected ： true
                            if(allResourceId==partResourceId){
                                resourceMap.put("selected","1");
                                break;
                            }else{
                                resourceMap.put("selected","0");
                            }
                        }
                    }else{
                        resourceMap.put("selected","0");
                    }
                    inputList.add(resourceMap);
                }
            }
            returnMapList.put("resourceList",inputList);
            logger.info("查询角色资源信息成功:{}",returnMapList);
            return ResponseResult.success(returnMapList);
        } catch (Exception e) {
            logger.error("查询角色资源信息异常",e);
            e.printStackTrace();
            return ResponseResult.fail("查询失败");
        }
    }

    /**
     * 根据角色信息查询角色与资源的关联信息列表
     * @param jsonObject 包含角色信息查询条件
     * @return  符合查询条件的角色与公司的相关信息列表
     */
    @ApiOperation(value="根据角色信息查询角色与资源的关联信息列表", notes="RCompanyRole")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "角色ID"),
            @ApiImplicitParam(name = "rName", value = "角色名称"),
            @ApiImplicitParam(name = "rCode", value = "角色code"),
            @ApiImplicitParam(name = "state", value = "角色状态"),
            @ApiImplicitParam(name = "serial", value = "显示顺序"),
            @ApiImplicitParam(name = "description", value = "备注"),
            @ApiImplicitParam(name = "updateTime", value = "更新时间")
    })
    @PostMapping("getRoleResourceInfoListByRoleCondition")
    public ResponseResult getRoleResourceInfoListByRoleCondition(@RequestBody JSONObject jsonObject){

        List<Map<String,Object>> all_list = new ArrayList<Map<String,Object>>();
        Integer id=jsonObject.getInteger("id");
        String rName=jsonObject.getString("rName");
        String rCode=jsonObject.getString("rCode");
        Integer state=jsonObject.getInteger("state");
        Integer serial=jsonObject.getInteger("serial");
        String description=jsonObject.getString("description");
        String updateTime=jsonObject.getString("updateTime");
        TRole tRole=new TRole();
        tRole.setId(id);
        tRole.setrName(rName);
        tRole.setrCode(rCode);
        tRole.setState(state);
        tRole.setSerial(serial);
        tRole.setDescription(description);
        tRole.setUpdateTime(updateTime);
        try {
            //根据条件查询角色信息列表
            List<TRole> roleList=roleService.selectRoleByCondition(tRole);
            if(!ConstentUtil.isEmpty(roleList)){
                String stringBuffer="";
                for(TRole tRole1 : roleList){
                    stringBuffer +=tRole1.getId()+",";
                }
                stringBuffer= stringBuffer.substring(0,stringBuffer.length()-1).trim();
                List li=ConstentUtil.strToList(stringBuffer);

                List<Map<String,Object>> tResourceList= tResourceService.selectTReSourceInfoListByRoleIds(li);
                if(!ConstentUtil.isEmpty(tResourceList)){

                    String[] strs = stringBuffer.split(",");
                    for (int j = 0; j < strs.length; j++) {
                        HashMap<String, Object> hm = new HashMap<>();
                        List list1 = new ArrayList();
                        for (int i = 0; i < tResourceList.size(); i++) {
                            if(strs[j].equals(tResourceList.get(i).get("roleId").toString())) {
                                hm.put("roleId", strs[j]);
                                hm.put("rName", tResourceList.get(i).get("rName").toString());
                                list1.add(tResourceList.get(i));
                                hm.put("data",list1);
                            }
                        }
                        if(hm.size()!=0){
                            all_list.add(hm);
                        }
                    }
                }
            }
            logger.info("查询角色与资源信息成功:{}",all_list);
            return ResponseResult.success(all_list);
        } catch (Exception e) {
            logger.error("查询角色与资源信息异常:",e);
            e.printStackTrace();
            return ResponseResult.fail("查询失败");
        }
    }
}